package io.gitee.skyarthur1987.leporidae.utils.base;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Type;

/**
 * 基于 google gson 的 json 工具类
 * Created by skyarthur on 2023/1/25
 */
@Slf4j
public class JsonUtils {
    private static final Gson GSON;
    private static final Gson GSON_DEFAULT;

    static {
        GSON_DEFAULT = getGB().create();
        GSON = getGB().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
    }

    private static GsonBuilder getGB() {
        return new GsonBuilder().disableHtmlEscaping().enableComplexMapKeySerialization();
    }

    public static <T> T fromJson(String json, Class<T> classOfT) {
        try {
            return GSON_DEFAULT.fromJson(json, classOfT);
        } catch (Exception e) {
            log.warn("from json meet ex:", e);
            return GSON.fromJson(json, classOfT);
        }
    }

    public static <T> T fromJson(String json, Type typeOfT) {
        try {
            return GSON_DEFAULT.fromJson(json, typeOfT);
        } catch (Exception e) {
            log.warn("from json meet ex:", e);
            return GSON.fromJson(json, typeOfT);
        }
    }


    public static String toJson(Object o) {
        return GSON_DEFAULT.toJson(o);
    }

    public static String toPrettyPrintJson(Object o) {
        return getGB().setPrettyPrinting().create().toJson(o);
    }

    public static JsonElement parseJson(String json) {
        return JsonParser.parseString(json);
    }
}
